package uform.model.value;

import thx.util.Result;
import thx.error.Error;
using thx.util.Results;

class BoolType extends ValueType<Bool>
{
	static var _re = ~/^\s*(true|false|1|0|ok|yes|no|y|n|on|off)\s*/im;
	public function new()
	{
		super();
	}
	
	override function validateType(value : Dynamic) : Result
	{
		if (Std.is(value, Bool))
			return Result.Ok;
		else
			return "expected type {0} but was {1}".failure(["Bool", Types.typeName(value)]);
	}
	
	override function _parse(s : String, ?ref : { s : String }) : Bool
	{
		if (!_re.match(s))
			throw new Error("unable to parse bool value '{0:T,20}'", s);
		
		if (null != ref)
			ref.s = _re.matchedRight();
		
		switch(_re.matched(1).toLowerCase())
		{
			case 'true', '1', 'ok', 'y', 'yes', 'on':
				return true;
			case 'false', '0', 'n', 'no', 'off':
				return false;
			default:
				return throw new Error("unable to deal with value '{0}'", _re.matched(1));
		}
	}
	
	override function render(value : Bool) : String
	{
		return value ? 'true' : 'false';
	}
}